package edu.faytechcc.csc.gui.server;

import com.sun.rowset.CachedRowSetImpl;
import edu.faytechcc.csc.messages.NetworkConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * This class is used for asking the database a question.
 *
 * @author Stephanie Mckenzie and Jasmin Pastari
 */
public class AskQuery
{
    // the NetworkConnection used to send the object this class creates.
    private NetworkConnection streamConn;
    final String DB_URL = "jdbc:derby:ARGDB;create=false";

    /**
     * Constructor that accepts a NetworkConnection
     * 
     * @param conn 
     */
    public AskQuery(NetworkConnection conn)
    {
        this.streamConn = conn;
    }

    /**
     * Ask the database a query.
     */
    public void AskGeneralQuery(String criteria)
    {
        try
        {
            Connection conn = DriverManager.getConnection(DB_URL);

            Statement stmt = conn.createStatement();

            String sqlStatement = criteria;
            ResultSet result = stmt.executeQuery(sqlStatement);
            CachedRowSetImpl rowSet = new CachedRowSetImpl();
            rowSet.populate(result);


            streamConn.sendObject(rowSet);

        } catch (Exception ex)
        {
            System.out.println("ERROR: " + ex.getMessage());
        }
    }
}
